/**
 * Created by wry on 2015/2/10.
 */

'use strict';

angular.module('backofficeApp.customerManager.controllers', []).
    controller('customerListCtrl', ['$scope', 'customerService', 'CommunityService', '$http', '$location', function ($scope, customerService, communityService, $http, $location) {

        $scope.$on('$viewContentLoaded', function () {
            $scope.communityLabelList = communityService.getAllCommunityService();
        });

        $scope.sendMessage = function (message) {
            if (message == null) {
                alert('请选择小区')
            } else if (message.communityId == null) {
                alert('请选择小区')
            } else if (message.msg == null) {
                alert('请输入内容')
            } else {
                var v = customerService.sendMessageService(message);
                alert('发送成功')
            }
        };

        $scope.currentPage = 1;
        $scope.totalPage = 10;
        $scope.pageSize = 30;
        $scope.pages = [];

        var commId = '1';
        var sta = '1';

        $scope.getUserList = function (communityId, status, nickname) {
            if (communityId == null) {
                communityId = '1'
            }
            if (nickname == null || nickname == '') {
                nickname = '1';
            }
            if (status == '已通过') {
                status = true
                sta = '已通过';
            } else if (status == '未通过') {
                status = false;
                sta = '未通过';
            } else {
                status = '1';
            }

            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/users/getAuthenticationUserList/' + nickname + '/' + communityId + '/' + status + '/' + $scope.currentPage, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.userList = new Array();
                if (data.data != null) {
                    data.data.uList.forEach(function (re) {
                        if (re.imageURL != null)
                            re.imageURL = fastDfsHostIp + re.imageURL;
                        $scope.userList.push(re);
                    })
                }
                $scope.totalPage = data.data.totalPage;
            }).error(function () {
                $scope.userList = null;
            });
        };

        $scope.getUserList(commId, sta);

        $scope.clickStatus = function (user) {

            if (!user.user.roomUnit || user.user.roomUnit === "") {
                var str = "缺少资料";
                //var a1 = !user.user.roomNumber || user.roomNumber === "" ? "(房号)" : ""
                var a2 = !user.user.roomUnit || user.user.roomUnit === "" ? "(单元)" : ""
                alert(str + a2);
                return
            }
            var body;
            if (user.status) {
                body = {
                    "user": user.user.objId,
                    "community": user.community.objId,
                    "status": false
                }
            } else {
                body = {
                    "user": user.user.objId,
                    "community": user.community.objId,
                    "status": true
                }
            }
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/users/examineUserAuthenticate', body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (data.result.status == 1) {
                    $scope.getUserList(commId, sta);
                } else {
                    alert(data.result.message)
                }
            }).error(function () {
                $scope.userList = null;
            });

        };

        $scope.refusal = "亲爱的邻居，您好！为保证V认证用户是真实的本小区居民，希望您能够上传能够有效显示您家庭住址的资料（如水电煤账单或邮件地址单）。另外请重视图片质量。谢谢您的合作。"

        $scope.ClickRefusal = function (id, userId, communityId, message) {
            if (message == null) {
                alert('请输入决绝原因');
                return;
            }

            var body = {
                "message": message,
                "userId": userId,
                "community": communityId
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/users/refuseUserAuthenticate/' + id, body, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getUserList(commId, sta);
            }).error(function () {
                $scope.userList = null;
            });
        };

        $scope.onSelectPage = function (page) {
            $scope.currentPage = page;
            $scope.getUserList(commId, sta);
        };

    }]).controller('feedbackCtrl', ['$scope', '$http', 'CommunityService', function ($scope, $http, communityService) {

        $scope.$on('$viewContentLoaded', function () {
            $scope.communityLabelList = communityService.getAllCommunityService();
        });

        var commId = '1';

        $scope.getFeedBackList = function (communityId) {
            if (communityId == null) {
                communityId = '1'
            }
            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/Systems/getFeedbackList/' + communityId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.feedbackList = data.data;

            }).error(function () {
                $scope.feedbackList = null;
            });
        };

        $scope.getFeedBackList(commId);

    }]).controller('supplementCtrl', ['$scope', '$http', 'CommunityService', '$location', function ($scope, $http, communityService, $location) {

        $scope.$on('$viewContentLoaded', function () {
            $scope.communityLabelList = communityService.getAllCommunityService();
        });

        var commId = '1';

        $scope.getSupplementList = function (communityId) {
            if (communityId == null) {
                communityId = '1'
            }
            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/communities/getCommunitySupplementList/' + communityId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                for (var i = 0; i < data.data.length; i++) {
                    if (data.data[i].status == true) {
                        data.data[i].status = '已处理'
                    } else {
                        data.data[i].status = '未处理'
                    }
                }

                $scope.supplementList = data.data;

            }).error(function () {
                $scope.supplementList = null;
            });
        };

        $scope.getSupplementList(commId);

        $scope.updateSupplementStatus = function (objId) {
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/communities/updateSupplementStatus/' + objId, {}).success(function (data) {
                $scope.getSupplementList(commId);
                //$scope.supplementList = communityService.getSupplementList(commId);
            }).error(function () {
            });

        }

        //跳转到服务修改页面
        $scope.gotoCommunityEditPage = function (objId) {
            $location.path('/community/edit/' + objId);
        };

        $scope.changeCommunityStatus = function (objId, status) {
            var input = {
                id: objId,
                status: status
            };
            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/marketing/changeCommunityStatus', input, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.communityLabelList = communityService.getAllCommunityService();
            }).error(function () {

            });
        };

        $scope.addCommunity = function () {
            $location.path('/community/add');
        };

    }]).controller('communityApplicationsCtrl', ['$scope', '$http', '$location', function ($scope, $http, $location) {

        $scope.$on('$viewContentLoaded', function () {

            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/marketing/getCommunityApplications', {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.communityLabelList = data.data;
            }).error(function () {

            });
        });


    }]).controller('communityAddCtrl', ['$scope', '$http', 'CommunityService', '$location', function ($scope, $http, communityService, $location) {


        function datePicker(id) {
            function d(id) {
                var self = this;
                $(id).datepicker({
                    format: 'yyyy-mm-dd',
                    autoclose: true,
                    forceParse: false
                }).on('changeDate', function (e) {
                    self.date = e.date;
                }).on('show', function (e) {
                    $(".datepicker.datepicker-dropdown.dropdown-menu").css("z-index", "10000");
                });
            }

            d.prototype.getValue = function () {
                if (this.date == null) {
                    return null;
                }
                return this.date.setHours(0, 0, 0, 0)
            }
            var date = new d(id);
            return date;
        };

        $scope.effectiveDate = datePicker('#effective');

        $scope.selectFile = function (files) {
            $scope.image = files[0]
        };

        $scope.city = '上海';

        //保存小区
        $scope.saveCommunity = function (community) {
            if (!community.name || !community.address || !$scope.image || !community.households) {
                return;
            }
            var fd = new FormData();
            fd.append('image1', $scope.image);
            fd.append('name', community.name);
            fd.append('address', community.address);
            fd.append('households', community.households);
            fd.append('lng', community.lng);
            fd.append('lat', community.lat);
            fd.append('city', $scope.city);
            fd.append('effectiveDate', $scope.effectiveDate.getValue());

            if (community.unitSwitch != null) {
                fd.append('unitSwitch', community.unitSwitch);
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/marketing/addCommunity', fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            }).success(function (data) {
                $location.path('/community');
            }).error(function (data) {
            });
        };

        $scope.cancelAddCommunity = function () {
            $location.path('/community');
        };

        $("#name_search").autocomplete({
            // 通过函数来获取并处理数据源
            source: function (request, response) {
                var keyword = request.term;
                var names = [];
                $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/marketing/searchCommunityByName/' + keyword + '/' + $scope.city, {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.communityList = data.data;

                    $scope.communityList.forEach(function (community) {
                        var temp = {
                            label: community.name,
                            id: community.id
                        };
                        names.push(temp);
                    });
                    response(names);
                }).error(function (data) {
                    response(names);
                });
            },
            select: function (event, ui) {
                var community = $scope.communityList[ui.item.id];

                //$scope.community = {
                //    name: community.name,
                //    address: community.address,
                //    lng: community.lng,
                //    lat: community.lat
                //}
                document.getElementById('community_address').value = community.address;
                document.getElementById('community_lng').value = community.lng;
                document.getElementById('community_lat').value = community.lat;

                $scope.community.name = community.name;
                $scope.community.address = community.address;
                $scope.community.lng = community.lng;
                $scope.community.lat = community.lat;

                //$('#community_address').attr("value",community.address);
            }
        });


    }]).controller('communityEditCtrl', ['$scope', '$routeParams', '$http', '$location', function ($scope, $routeParams, $http, $location) {

        function datePicker(id) {
            function d(id) {
                var self = this;
                $(id).datepicker({
                    format: 'yyyy-mm-dd',
                    autoclose: true,
                    forceParse: false
                }).on('changeDate', function (e) {
                    self.date = e.date;
                }).on('show', function (e) {
                    $(".datepicker.datepicker-dropdown.dropdown-menu").css("z-index", "10000");
                });
            }

            d.prototype.getValue = function () {
                if (this.date == null) {
                    return null;
                }
                return this.date.setHours(0, 0, 0, 0)
            }
            var date = new d(id);
            return date;
        };

        $scope.effectiveDate = datePicker('#effective');

        $scope.getSupplementList = function () {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/communities/backOfficeGetCommunityDetail/' + $routeParams.objId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.community = data.data;
                //$scope.community.dateEffective = data.data.dateEffective.getDate();
                if($scope.community.dateEffective) {
                    $("#effective").val(new Date($scope.community.dateEffective).format('yyyy-MM-dd'));
                }
            }).error(function () {
                $scope.community = null;
            });
        };
        $scope.getSupplementList();

        $scope.addPhoneNo = function () {
            var temp = {
                "name": "",
                "phoneNo": ""
            };
            $scope.community.phoneList.push(temp);
        };

        $scope.deletePhoneNo = function (index) {
            $scope.community.phoneList.remove(index);
        };

        Array.prototype.remove = function (dx) {
            if (isNaN(dx) || dx > this.length) {
                return false;
            }
            for (var i = 0, n = 0; i < this.length; i++) {
                if (this[i] != this[dx]) {
                    this[n++] = this[i]
                }
            }
            this.length -= 1
        };

        var reader = null;
        if (FileReader) {
            reader = new FileReader();
        } else {
            alert("浏览器暂时不支持FileReader");
        }

        $scope.selectFile = function (files) {
            $scope.image = files[0];

            reader.readAsDataURL(files[0]);
            reader.onload = function () {
                $('#logo').attr("src", reader.result);
            };
        };

        //更新服务
        $scope.updateCommunity = function () {
            console.log($scope.community);
            if ($scope.community.communityName == null || $scope.community.communityName == '') {
                alert('请输入小区名称');
                return;
            };
            if ($scope.community.communityAddress == null || $scope.community.communityAddress == '') {
                alert('请输入小区地址');
                return;
            };
            if ($("#effective").val() == null || $("#effective").val() == '') {
                alert('请输入小区生效日期');
                return;
            };
            if ($scope.community.communityPostCode == null || $scope.community.communityPostCode == '') {
                alert('请输入小区邮编');
                return;
            };

            var flag = false;
            $scope.community.phoneList.forEach(function (phone) {
                if (phone.name == '' || phone.phoneNo == '') {
                    flag = true;
                }
            });
            if (flag) {
                alert('请补全常用电话或删除空的栏目');
                return;
            }

            var fd = new FormData();
            if ($scope.image != null)
                fd.append('image1', $scope.image);
            fd.append('communityName', $scope.community.communityName);
            fd.append('communityAddress', $scope.community.communityAddress);
            fd.append('households', $scope.community.households);
            fd.append('communityPostCode', $scope.community.communityPostCode);
            fd.append('phoneList', JSON.stringify($scope.community.phoneList));
            fd.append('unitSwitch',$scope.community.unitSwitch);
            fd.append('dateEffective', new Date($("#effective").val()));

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/communities/updateCommunity/' + $routeParams.objId, fd, {
                    transformRequest: angular.identity,
                    headers: {'Content-Type': undefined}
                }
            ).success(function (data) {
                    $location.path('/community');
                }).error(function () {
                });
        };

        //返回到小区列表
        $scope.gotoCommunityListPage = function () {
            $location.path('/community');
        }

    }]).controller('activityCtrl', ['$scope', '$http', '$location', 'CommunityService', function ($scope, $http, $location, communityService) {

        $scope.$on('$viewContentLoaded', function () {
            $scope.communityLabelList = communityService.getAllCommunityService();
        });

        var lotteryId = '';

        var commId;

        //获取抽奖活动
        $scope.getLottery = function (communityId) {
            if (communityId == null) {
                $scope.lottery = [];
                return;
            }
            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getLotteryActivity/' + communityId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (data.data != null) {
                    var result = data.data;
                    result.weekLottery.forEach(function (lottery) {
                        lottery.lotteryTickets.forEach(function (tic) {

                            switch (tic.ranking) {
                                case 6:
                                    lottery['one'] = tic;
                                    break;
                                case 5:
                                    lottery['two'] = tic;
                                    break;
                                case 4:
                                    lottery['three'] = tic;
                                    break;
                                case 3:
                                    lottery['four'] = tic;
                                    break;
                                case 2:
                                    lottery['five'] = tic;
                                    break;
                                case 1:
                                    lottery['six'] = tic;
                                    break;
                            }
                        })
                    });
                    $scope.lottery = result;
                    lotteryId = result.objId;
                } else {
                    $scope.lottery = []
                }
            }).error(function () {
            });
        };


        //抽奖
        $scope.lotteryDraw = function (weekId, rank) {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/lotteryUser/' + lotteryId + '/' + weekId + '/' + rank, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                if (data.data != null) {
                    $scope.lottery.weekLottery.forEach(function (lottery) {
                        lottery.lotteryTickets.forEach(function (tic) {
                            switch (rank) {
                                case 6:
                                    lottery['one'] = data.data;
                                    break;
                                case 5:
                                    lottery['two'] = data.data;
                                    break;
                                case 4:
                                    lottery['three'] = data.data;
                                    break;
                                case 3:
                                    lottery['four'] = data.data;
                                    break;
                                case 2:
                                    lottery['five'] = data.data;
                                    break;
                                case 1:
                                    lottery['six'] = data.data;
                                    break;
                            }
                        })
                    });
                } else {
                    alert('无抽奖号码')
                }

            }).error(function () {

            });
        };

        $scope.openLottery = function (weekId) {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/openLottery/' + lotteryId + '/' + weekId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getLottery(commId);
            }).error(function () {
                $scope.getLottery(commId);
            });
        };

        //查看中奖用户
        $scope.getLuckyUser = function (weekId) {
            $scope.user = null;
            $('#exampleModal').modal('toggle');
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/lottery/getLuckyUser/' + lotteryId + '/' + weekId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                var result = data.data;
                var imageURL = ''
                if (result.images != null && result.images.length > 0) {
                    imageURL = fastDfsHostIp + result.images[0].imageURL
                }
                result['portraitURL'] = fastDfsHostIp + imageURL;
                $scope.user = result;
            }).error(function () {
            });
        }

        $scope.addLottery = function () {

        }

    }]).
    controller('noticeCtrl', ['$scope', '$http', 'CommunityService', '$location', function ($scope, $http, communityService, $location) {

        $scope.$on('$viewContentLoaded', function () {
            $scope.communityLabelList = communityService.getAllCommunityService();
        });

        var commId = '1';

        $scope.getNoticeList = function (communityId) {
            if (communityId == null) {
                communityId = '1'
            }
            commId = communityId;
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/communities/getAllCommunityNotice/' + communityId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {

                var result = data.data;

                $scope.noticeList = result;
                $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/question/getFreshNewsQuestion', {
                    headers: {'Content-Type': 'application/json;charset=utf-8'}
                }).success(function (data) {
                    $scope.freshQuestion = data.data;

                    result.forEach(function (question) {
                        $scope.freshQuestion.forEach(function (fresh) {
                            if (question.objId == fresh.newsId) {
                                question['isFresh'] = true
                            }
                        });
                    });
                    $scope.noticeList = result;
                }).error(function () {
                });

            }).error(function () {
                $scope.noticeList = null;
            });
        };

        $scope.getNoticeList(commId);

        $scope.addNoticeToNews = function (communityId, noticeId) {
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/communities/addNoticeToFresh/' + communityId + '/' + noticeId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getNoticeList(commId);

            }).error(function () {
            });
        };

        $scope.addNoticeRoute = function () {
            $location.path('/addNotice');
        };

        $scope.deleteNotice = function (noticeId) {
            bootbox.confirm('确定删除此公告？', function (result) {
                if (result == true) {
                    $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/communities/deleteNotice/' + noticeId, {
                        headers: {'Content-Type': 'application/json;charset=utf-8'}
                    }).success(function (data) {
                        $scope.getNoticeList(commId);
                    }).error(function () {
                    });
                }
            }).find("div.modal-dialog").css({width: '30%'});
        };

        $scope.editNotice = function (noticeId) {
            $location.path('notice/' + noticeId)
        };

        $scope.previewNotice = function (url) {
            var body = document.getElementById("qrBody");
            var div = document.getElementById("qrcodeCanvas");

            body.removeChild(div);

            var newMask = document.createElement("div");
            newMask.id = "qrcodeCanvas";
            body.appendChild(newMask);

            $('#qrDiv').modal('show');
            $('#qrcodeCanvas').qrcode(url);
        };

        $scope.setNoticeStatus = function (id, status) {
            var opt = {
                id: id,
                status: status
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/backoffice/communities/setNoticeStatus', opt, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.getNoticeList(commId);
            }).error(function () {
                $scope.getNoticeList(commId);
            });
        }

    }]).
    controller('noticeAddCtrl', ['$scope', '$http', 'CommunityService', '$location', function ($scope, $http, communityService, $location) {

        $scope.$on('$viewContentLoaded', function () {
            $scope.communityLabelList = communityService.getAllCommunityService();
            $scope.communityIds = '';
            $scope.message = '发布公告'
        });

        KindEditor.ready(function (K) {
            window.kinEdit = K.create('#editor_id', {
                uploadJson: '/rest/v1.0/Systems/uploadImages'
            });
        });

        $scope.data = new Array();
        $scope.toggle = function (ck, objId) {
            if (ck == null && $scope.communityIds.indexOf(objId) != -1) {
                ck = true;
            }
            !ck ? $scope.data.push(objId) : $scope.data.remove(objId);
        };

        $scope.editor = '';

        $scope.clearEditor = function () {
            kinEdit.html('')
        };
        $scope.items = [];
        $scope.addFile = function () {
            $scope.items.push(new Date());
        };

        $scope.deleteFile = function (item, path) {
            $scope.items.remove(item);
            var array = path.split('\\');
            var name = array[array.length - 1];

            $scope.images.forEach(function (image) {
                if (image.name == name) {
                    $scope.images.remove(image);
                }
            })
        };
        $scope.images = new Array();


        $scope.selectFile = function (files) {
            for (var i = 0; i < $scope.images.length; i++) {
                var image = $scope.images[i];
                if (image != null && image.name == files[0].name) {
                    image.file = files[0];
                    return;
                }
            }
            var temp = {
                "name": files[0].name,
                "file": files[0]
            };
            $scope.images.push(temp);

        };

        $scope.uploadFile = function () {
            $scope.fd = new FormData();
            for (var i = 0; i < $scope.images.length; i++) {
                var name = 'image' + (i + 1);
                $scope.fd.append(name, $scope.images[i].file);
            }

            $http.post('http://' + backOfficeHost + '/rest/v1.0/Systems/oldUploadImages', $scope.fd, {
                transformRequest: angular.identity,
                headers: {'Content-Type': undefined}
            }).success(function (data) {
                $scope.urls = new Array();
                if (data.data != null) {
                    data.data.forEach(function (url) {
                        $scope.urls.push(fastDfsHostIp + url);
                    })
                }
            }).error(function () {
                $scope.msg = 'error';
            });

            //topicService.uploadImages($scope.images);
        };

        $scope.selectImage = function (item, name) {

            for (var i = 0; i < $scope.images.length; i++) {
                var image = $scope.images[i];
                if (image != null && image.item == item) {
                    image.name = name;
                    return;
                }
            }
            var temp = {
                "item": item,
                "name": name
            };
            $scope.images.push(temp);
        };

        $scope.postNotice = function (communityId, notice) {

            if (notice.title == null || notice.title == '') {
                alert('请输入标题');
                return;
            }
            if (notice.imageURL == null || notice.imageURL == '') {
                alert('请输入壁纸');
                return;
            }
            if (kinEdit.isEmpty()) {
                alert('请输入内容');
                return;
            }

            var html = kinEdit.html();

            var a = html.replace(/width=.[0-9]*\"/g, '');
            a = a.replace(/height=.[0-9]*\"/g, '');
            //a = a.replace(/style=\".*px\;\"/g, 'style=\"display:block;max-width:100%;\"');
            a = a.replace(/\<img/g, '<img style=\"display:block;max-width:100%;\"');
            a = a.replace(/\<embed/g, '<embed style=\"display:block;max-width:100%;\"');

            var temp = {
                "community": $scope.data,
                "desc": a,
                "title": notice.title,
                "imageURL": notice.imageURL
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/communities/postCommunityBulletin/1/1', temp, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $location.path('/notice')
            }).error(function () {
                alert('发布失败')
            });

        };

    }]).controller('noticeEditCtrl', ['$scope', '$routeParams', 'CommunityService', '$http', '$location', function ($scope, $routeParams, communityService, $http, $location) {

        KindEditor.ready(function (K) {
            window.kinEdit = K.create('#editor_id', {
                uploadJson: '/rest/v1.0/Systems/uploadImages'
            });
        });

        $scope.data = [];

        $scope.$on('$viewContentLoaded', function () {
            $scope.message = '更新公告';
            $scope.communityLabelList = communityService.getAllCommunityService();
            $http.get('http://' + backOfficeHost + '/rest/v1.0/backoffice/communities/getNoticeById/' + $routeParams.noticeId, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $scope.notice = data.data;
                $scope.data = $scope.notice.community;
                $scope.communityIds = '';
                $scope.notice.community.forEach(function (temp) {
                    $scope.communityIds += temp;
                });
                kinEdit.html($scope.notice.desc)
            }).error(function () {
            });
        });

        $scope.toggle = function (ck, objId) {
            if (ck == null && $scope.communityIds.indexOf(objId) != -1) {
                ck = true;
            }
            !ck ? $scope.data.push(objId) : $scope.data.remove(objId);
        };


        $scope.postNotice = function (communityId, notice) {

            if (notice.title == null || notice.title == '') {
                alert('请输入标题');
                return;
            }
            if (notice.imageURL == null || notice.imageURL == '') {
                alert('请输入壁纸');
                return;
            }
            if (kinEdit.isEmpty()) {
                alert('请输入内容');
                return;
            }

            var html = kinEdit.html();

            var a = html.replace(/width=.[0-9]*\"/g, '');
            a = a.replace(/height=.[0-9]*\"/g, '');
            a = a.replace(/style=\".*px\;\"/g, 'style=\"display:block;max-width:100%;\"');
            a = a.replace(/\<img/g, '<img style=\"display:block;max-width:100%;\"');
            a = a.replace(/\<embed/g, '<embed style=\"display:block;max-width:100%;\"');

            var temp = {
                "id": notice.objId,
                "community": $scope.data,
                "desc": a,
                "title": notice.title,
                "imageURL": notice.imageURL
            };

            $http.post('http://' + backOfficeHost + '/rest/v1.0/communities/postCommunityBulletin/1/1', temp, {
                headers: {'Content-Type': 'application/json;charset=utf-8'}
            }).success(function (data) {
                $location.path('/notice')
            }).error(function () {
                alert('更新失败')
            });
        };
    }])
    .directive('paging', function () {
        return {
            restrict: 'E',
            //scope: {
            //    numPages: '=',
            //    currentPage: '=',
            //    onSelectPage: '&'
            //},
            template: '',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('currentPage', function (value) {
                    scope.pages = [];
                    for (var i = value - 5 > 0 ? value - 5 : 1; i <= (value + 5 > scope.totalPage ? scope.totalPage : value + 5); i++) {
                        scope.pages.push(i);
                    }
                });
                scope.$watch('totalPage', function (value) {
                    scope.pages = [];
                    for (var i = scope.currentPage - 5 > 0 ? scope.currentPage - 5 : 1; i <= (scope.currentPage + 5 > value ? value : scope.currentPage + 5); i++) {
                        scope.pages.push(i);
                    }
                });

                scope.isActive = function (page) {
                    return scope.currentPage === page;
                };
                scope.selectPage = function (page) {
                    if (!scope.isActive(page)) {
                        scope.currentPage = page;
                        scope.onSelectPage(page);
                    }
                };
                scope.selectPrevious = function () {
                    if (!scope.noPrevious()) {
                        scope.selectPage(scope.currentPage - 1);
                    }
                };
                scope.selectNext = function () {
                    if (!scope.noNext()) {
                        scope.selectPage(scope.currentPage + 1);
                    }
                };
                scope.noPrevious = function () {
                    return scope.currentPage == 1;
                };
                scope.noNext = function () {
                    return scope.currentPage == scope.totalPage;
                };

            }
        };
    })


